<template>
    <div id="container">
        <a-page-header
                style="border: 1px solid rgb(235, 237, 240)"
        >
            <a-form :form="form" @submit="onSubmitTitle" layout="inline" slot="title">
                <a-form-item :help="title ? '' : '请输入标题'" :validate-status="title ? '' : 'error'"
                             label="标题">
                    <a-input
                            @blur="onSubmitTitle"
                            placeholder="请输入标题"
                            ref="titleInput"
                            v-model="title"
                            v-show="editingTitle"
                    />
                    <span v-show="!editingTitle">
                        <span style="margin-right: 1rem">{{title}}</span>
                        <a-icon @click="editTitle" class="edit-icon" type="edit"/>
                    </span>
                </a-form-item>
            </a-form>
            <template slot="extra">
                <a-tooltip placement="bottom">
                    <template slot="title">
                        <span>内容暂存后仍然需要点击提交后才会将文章提交审核<br/><strong>需等待暂存后才能提交</strong></span>
                    </template>
                    <a-alert :message="statusMessage[status]" :showIcon="true" :type="status"
                             style="display: inline-block"/>
                </a-tooltip>
                <a-button @click="submitArticle" style="border-radius: 25px" type="primary">提交</a-button>
            </template>
        </a-page-header>
        <mavon-editor
                :boxShadow="true"
                :ishljs="true"
                :toolbars="toolbars"
                :value="value"
                ref="editor"
                @change="onChange"
                @imgAdd="uploadImg"
                @imgDel="deleteImg"
                id="editor"/>
    </div>
</template>

<script>
    import {Alert, Button, Form, Icon, Input, message, PageHeader, Tooltip} from "ant-design-vue";
    import axios from "axios";

    const toolbars = {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: false, // 展示html源码
        help: false, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: false, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
    };

    export default {
        name: "Editor",
        components: {
            APageHeader: PageHeader,
            AInput: Input,
            AForm: Form,
            AFormItem: Form.Item,
            AIcon: Icon,
            AButton: Button,
            AAlert: Alert,
            ATooltip: Tooltip,
        },
        data() {
            return {
                toolbars: toolbars,
                editingTitle: true,
                form: this.$form.createForm(this, {name: 'title'}),
                title: "",
                value: "",
                status: "info",
                statusMessage: {
                    info: "文章内容未暂存",
                    success: "文章内容已暂存",
                    warning: "文章内容暂存中",
                    error: "文章内容暂存失败，请勿刷新或关闭页面，并在编写完成后提交"
                },
                saveContentTimeout: null,
                writed: false,
            }
        },
        mounted() {
            // 阻止用户关闭页面
            window.onbeforeunload = this.beforeunloadHandler;

            let editingContent = JSON.parse(localStorage.getItem("editingContent") || "{}");
            if (editingContent.content) {
                this.$confirm({
                    title: '继续编辑',
                    content: '检测到您上次还有文章未提交，是否继续编辑？',
                    okText: '确认',
                    cancelText: '取消',
                    keyboard: false,
                    onOk: () => {
                        this.value = editingContent.content;
                        this.title = editingContent.title;
                    }
                });
            }
        },
        methods: {
            onSubmitTitle: function (evt) {
                evt.preventDefault();
                if (this.title !== "") {
                    this.editingTitle = false;
                }
            },
            editTitle: function () {
                this.editingTitle = true;
                // 如果不延时会聚焦不了
                setTimeout(() => {
                    this.$refs.titleInput.focus();
                }, 1);
            },
            onChange: function (value) {
                this.writed = true;
                // 监听用户输入，并且在1s之后自动暂存到localStorage
                clearTimeout(this.saveContentTimeout);
                this.status = "info";
                this.saveContentTimeout = setTimeout(() => {
                    try {
                        this.status = "warning";
                        localStorage.setItem("editingContent", JSON.stringify({'title': this.title, 'content': value}));
                        this.status = "success";
                    } catch (e) {
                        console.error(e);
                        this.status = "error"
                    }
                }, 1000);
            },
            uploadImg: function (pos, $file) {
                // 将图片上传到服务器
                let formdata = new FormData();
                formdata.append('image', $file);
                axios.post("/upload_img/", formdata, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                }).then(response => {  // ES6的写法
                    this.$refs.editor.$img2Url(pos, response.data);  // 修改图片链接
                })
            },
            deleteImg: function (pos) {
                axios.delete("/upload_img/", {
                    data: {
                        link: pos[0]
                    }
                })
            },
            submitArticle: function () {
                if (this.status !== "success" && this.writed) {
                    return message.warning("请等待内容暂存后再提交");
                }

                // 将文章内容提交
                let article = JSON.parse(localStorage.getItem("editingContent") || "{}");
                if (!this.title || !article.content) {
                    return message.error(!this.title ? '请填写文章标题' : "请填写文章内容");
                }
                axios.post("/article/create/", {
                    title: this.title,
                    content: article.content
                }).then(response => {
                    console.log(response.data);
                    localStorage.removeItem("editingContent");
                    window.onbeforeunload = null;
                    window.close();
                })
            },
            beforeunloadHandler: function (e) {
                if (this.status !== "success") {
                    return (e || window.event).returnValue = '确认离开？！'
                }
            }
        }
    }
</script>

<style scoped>
    #container {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }

    #editor {
        height: 100%;
    }

    .edit-icon {
        cursor: pointer;
    }

    >>> .ant-form-item-with-help {
        margin-bottom: 0;
    }

    >>> .ant-alert {
        border: unset;
        background-color: unset;
    }

    >>> .ant-alert .ant-alert-message {
        color: #9a9a9a;
    }
</style>